package com.easylinkin.linkappapi.openapi.controller;

import com.alibaba.fastjson.JSON;
import com.easylinkin.linkappapi.annotation.CommonOperateLogAnnotate;
import com.easylinkin.linkappapi.openapi.event.DeviceUnitVersionUpdateEvent;
import com.easylinkin.linkappapi.openapi.service.SynchronizationLinkthingService;
import com.easylinkin.linkappapi.operatelog.constant.LogConstant.LogModule;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liuming
 * @since 2020-04-17
 */
@RestController
@Api(value="同步LinkThings",tags={"同步LinkThings"})
public class SynchronizationLinkthingController {
	@Autowired
	SynchronizationLinkthingService synchronizationLinkthingService ;
	
	private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(SynchronizationLinkthingController.class);
	
	@Resource
	private ApplicationContext context;

	@ApiOperation("主动同步设备型号")
	@RequestMapping(value = "/synchronizationLinkthing", produces = "application/json;charset=UTF-8")
	@CommonOperateLogAnnotate(module = LogModule.SYNCHRONIZATION, desc = "主动同步设备型号")
	public RestMessage synchronizationLinkthing() {
		return RestBuilders.successBuilder(synchronizationLinkthingService.synchronizationDeviceData()).build();
	}

	@ApiOperation("主动同步设备型号及设备")
	@RequestMapping(value = "/synchronizeDeviceUnitAndDevicesByProject", produces = "application/json;charset=UTF-8")
	@CommonOperateLogAnnotate(module = LogModule.SYNCHRONIZATION, desc = "主动同步设备型号及设备")
	public RestMessage synchronizeDeviceUnitByProject() {
		try {
			// 同步设备型号
			Map<String, List> deviceUnitmap = synchronizationLinkthingService.synchronizeDeviceUnitByProject();
			// 同步设备
			Map<String, List> devicemap = synchronizationLinkthingService.getDevicesByProject();
			StringBuilder sb = new StringBuilder();
			if(deviceUnitmap!=null) {
				sb.append("AEP 未找到的设备型号个数:");
				sb.append(deviceUnitmap.get("noFindDeviceUnitList").size());
				sb.append("<br>");
				sb.append("AEP更新设备型号个数:");
				sb.append(deviceUnitmap.get("updateDeviceUnitList").size());
				sb.append("<br>");
			}
			if(devicemap!=null) {
				sb.append("新建设备个数:");
				sb.append(devicemap.get("add").size());
				sb.append("<br>");
				sb.append("更新设备个数:");
				sb.append(devicemap.get("update").size());
				sb.append("<br>");
				sb.append("错误设备个数:");
				sb.append(devicemap.get("error").size());
			}
			//设备型号更新触发数据一致性变更
			context.publishEvent(new DeviceUnitVersionUpdateEvent(deviceUnitmap));
			return RestBuilders.successBuilder().data(sb.toString()).build();
		} catch (UnsupportedEncodingException e) {
			return RestBuilders.failureBuilder().code("500").build();
		}
	}

	/**
	 * 前端，emp后端全局查询没地方用到该接口		注明：已弃用
	 * @return
	 */
	@Deprecated
	@ApiOperation("主动同步设备型号及设备-No-Login")
	@RequestMapping(value = "/synchronizeDeviceUnitAndDevicesByProjectNoLogin", produces = "application/json;charset=UTF-8")
	@CommonOperateLogAnnotate(module = LogModule.SYNCHRONIZATION, desc = "主动同步设备型号及设备-No-Login")
	public RestMessage synchronizeDeviceUnitAndDevicesByProjectNoLogin() {
		try {
			// 同步设备型号
			synchronizationLinkthingService.synchronizeDeviceUnitAndDevicesByProjectByTime();
			// 同步设备
			return RestBuilders.successBuilder("200").build();
		} catch (UnsupportedEncodingException e) {
			return RestBuilders.failureBuilder().code("500").build();
		}
	}


	/**
	 * 单个型号添加 增量会用到
	 * @param deviceUnitList
	 * @return
	 */
	@ApiOperation("实时同步设备型号")
	@PostMapping(value = "/synchronizationDeviceUnit", produces = "application/json;charset=UTF-8")
	@CommonOperateLogAnnotate(module = LogModule.SYNCHRONIZATION, desc = "实时同步设备型号")
	public RestMessage synchronizationDeviceUnit(@RequestBody List<com.easylinkin.linkappapi.openapi.dto.DeviceUnitDTO> deviceUnitList) {
		try {
			LOGGER.info("synchronizationDeviceUnit接口被调用,参数是:{}", JSON.toJSONString(deviceUnitList));
			synchronizationLinkthingService.synchronizeDeviceUnitAttributeServiceParamMultiVersion(deviceUnitList);
			return RestBuilders.successBuilder("200").build();
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error(e.getMessage(), e);
			return RestBuilders.failureBuilder().code("500").data(e.toString()).build();
		}
	}

	@ApiOperation("实时同步删除设备型号")
	@PostMapping(value = "/synchronizationDeleteDeviceUnit", produces = "application/json;charset=UTF-8")
	@CommonOperateLogAnnotate(module = LogModule.SYNCHRONIZATION, desc = "实时同步删除设备型号")
	public RestMessage synchronizationDeleteDeviceUnit(@RequestBody List<com.easylinkin.linkappapi.openapi.dto.DeviceUnitDTO> deviceUnitList){
		try {
			LOGGER.info("synchronizationDeleteDeviceUnit接口被调用,参数是:{}", JSON.toJSONString(deviceUnitList));
			synchronizationLinkthingService.synchronizeDeleteDeviceUnitAttributeServiceParamMultiVersion(deviceUnitList);
			return RestBuilders.successBuilder("200").build();
		} catch (Exception e) {
			LOGGER.error("call synchronizationDeleteDeviceUnit error:",e);
			return RestBuilders.failureBuilder().code("500").message(e.getMessage()).build();
		}
	}
}
